<?php

namespace App\Http\Controllers\API;

use App\Member;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class MemberController extends Controller
{
	/**
	 * Display a listing of the resource.
	 *
	 * @return \Illuminate\Http\Response
	 */
	public function index(Request $request)
	{

		$page = $request->input('page', 1);
		$pageSize = 5;
		$offset = ($page - 1) * $pageSize;
		$data['data'] = Member::where([])->offset($offset)->limit($pageSize)->get();
		$data['total_page'] = Member::where([])->count();
		if($data) {
			return [
				'code'    => 200,
				'message' => 'ok',
				'data'    => $data
			];
		} else {
			return [
				'code'    => 200,
				'message' => 'ok',
				'data'    => []
			];
		}

	}

	/**
	 * Store a newly created resource in storage.
	 *
	 * @param  \Illuminate\Http\Request $request
	 *
	 * @return \Illuminate\Http\Response
	 */
	public function store(Request $request)
	{
		$validator = Validator::make($request->all(), [
			'mobile' => 'required|unique:members',
			'mobile' => 'regex:/^1[345789][0-9]{9}$/',
			'email'  => 'required|email'
		]);
		if($validator->fails()) {
			return $this->jsonRes(0, "请检查传入参数");
		}
		//验证重复
		$membersData = Member::where('mobile', '=', $request->input('mobile'))->get(array('id'))->toArray();
		if(!empty($membersData)) {
			return $this->jsonRes(0, "手机号不能重复");
		}

		$memberDatas = Member::create($request->all());
		return $this->jsonRes(1, $memberDatas);
	}

	/**
	 * Display the specified resource.
	 *
	 * @param  int $id
	 *
	 * @return \Illuminate\Http\Response
	 */
	public function show(Member $member)
	{
		//
		return $this->jsonRes(1, $member);
	}

	/**
	 * Update the specified resource in storage.
	 *
	 * @param  \Illuminate\Http\Request $request
	 * @param  int                      $id
	 *
	 * @return \Illuminate\Http\Response
	 */
	public function update(Request $request, Member $member)
	{
		$member->update($request->all());
		return $this->jsonRes(1, $member);
	}

	/**
	 * Remove the specified resource from storage.
	 *
	 * @param  int $id
	 *
	 * @return \Illuminate\Http\Response
	 */
	public function destroy(Member $member)
	{
		$member->delete();
		return $this->jsonRes(1, '删除成功');
	}

	/**
	 * UPload the specified resource from storage.
	 *
	 * @param  int $id
	 *
	 * @return \Illuminate\Http\Response
	 */
	public function upload(Request $request)
	{
		print_r($_FILES);
	}
}
